package com.yjh.admin.controller.file;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import common.FTPUtils;
import common.FtpProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import util.R;

import java.io.IOException;

/**
 * 文件控制
 *
 * @author smithGuo
 * @date 2020-06-15 08:39:03
 */
@Component
@RestController
@AllArgsConstructor
@ApiModel(value = "文件控制" )
@EnableConfigurationProperties(FtpProperties.class)
@RequestMapping("/file")
@Slf4j
public class FileController {



    private final FtpProperties ftpProperties;

    /**
     * 上传文件
     * @param
     * @return R
     */
    @ApiOperation("上传文件")
    @PostMapping("/uploadFile")
    public R uploadFile(@RequestBody MultipartFile object ) throws IOException {
        log.info("上传文件大小"+object.getSize());
       // 生成文件名
        String fileUrl = StrUtil.format("{}.{}",
                IdUtil.simpleUUID(),
                FileUtil.extName(object.getOriginalFilename()));
        FTPUtils.uploadFile(ftpClient(),"/upload/", fileUrl,object.getInputStream(),ftpProperties.getWorkingDirectory());
        return new R<>(fileUrl);
    }



    /**
     * 登录FTP
     * @param
     * @return R
     */
    private FTPClient ftpClient(){
        FTPClient ftpClient = null;
        ftpClient = FTPUtils.loginFTP(ftpProperties.getHost(),ftpProperties.getPort(),ftpProperties.getUsername(),ftpProperties.getPassword());
        return ftpClient;
    }





}
